package Cn.Sarkar.Features

import io.ktor.application.ApplicationCallPipeline
import io.ktor.application.ApplicationFeature
import io.ktor.auth.HttpAuthHeader
import io.ktor.auth.UnauthorizedResponse
import io.ktor.http.HeaderValueParam
import io.ktor.response.ApplicationSendPipeline
import io.ktor.util.AttributeKey

object FixDigestProblem : ApplicationFeature<ApplicationCallPipeline, Unit, Unit> {
    override val key: AttributeKey<Unit> by lazy { AttributeKey<Unit>("FixDigestProblem") }

    override fun install(pipeline: ApplicationCallPipeline, configure: Unit.() -> Unit) {
        pipeline.sendPipeline.intercept(ApplicationSendPipeline.Before) {
            if (subject is UnauthorizedResponse) {
                val theSubject = (subject as UnauthorizedResponse)
                if (!(theSubject.challenges.size > 0)) return@intercept

                val authHeader = theSubject.challenges[0] as HttpAuthHeader.Parameterized
                val paramList = arrayOf(*authHeader.parameters.toTypedArray(), HeaderValueParam("qop", "auth")).toList()
                val proceedSubject = UnauthorizedResponse(HttpAuthHeader.Parameterized(authHeader.authScheme, paramList, authHeader.encoding))

                proceedWith(proceedSubject)
            }
        }
    }

}